<?php
/**
* Cache class file.
*
* @author Federico Ramirez <fedekiller@gmail.com>
* @link http://code.google.com/p/akaikiwi/
* @copyright Copyright &copy; 2008-2011 Federico Ramirez
* @license http://www.opensource.org/licenses/mit-license.php MIT Licence
*/

/*
* This class manages site cache in a action-based form
* You can enable cache in your controllers only in the actions you want
*/
class Cache {
	private $enabled;
	private $expiration_time;
	private $path;

	function __construct() {
		$config = AkaiKiwi::loadLib('Config');
		$this->path = $config->get_item('cachePath');
		$this->enabled = FALSE;

		if(!is_writable($this->path) && $this->enabled) {
			throw new AkaikiwiException('The cache directory is not writable.');
		}
	}

	/**
	 * Enables caching
	 * @param int $expiraton_time in minutes
	 */
	function enable($expiraton_time) {
		$this->enabled = TRUE;
		$this->expiration_time = $expiraton_time;
	}

	/**
	 * Initiates the cache.
	 * This will read the cache file if exists, and delete it if it has expired.
	 * It will then just show the data of the cache file and exit.
	 */
	function init() {
		$file = $this->path . '/' . md5(urlencode($_SERVER['REQUEST_URI']));
		if(file_exists($file)) {
			readfile($file);

			// Did it expire?
			if((int)file_get_contents($file.'_') < time()) {
				unlink($file);
				unlink('_'.$file);
			}

			// Calling exit will also flush all buffers started by ob_start
			exit();
		}
	}

	/**
	 * This will get all the contents of the buffer and save them
	 * if caching is enabled
	 */
	function write() {
		if($this->enabled) {
			$file = $this->path . '/' . md5(urlencode($_SERVER['REQUEST_URI']));
			$output = ob_get_contents();
			file_put_contents($file, $output);
			file_put_contents($file.'_', time() + $this->expiration_time * 60);
		}
	}

}
